class UsersController < ApplicationController
  before_action :signed_in_user,only:[:edit,:update,:index,:destroy,:following,:followers]
  before_action :correct_user,only:[:edit,:update]
  before_action :admin_user,only: :destroy

  def followers
    @title = "Followers"
    @user = User.find(params[:id])
    @users = @user.followers.paginate(page:params[:page])
    render 'show_follow'
  end

  def following
    @title = "Following"
    @user = User.find(params[:id])
    @users = @user.followed_users.paginate(page:params[:page])
    render 'show_follow'
  end
  
  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User destroyed."
    redirect_to users_url
  end

  def index
    @users = User.paginate(page:params[:page])
  end

  def update
    #@user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = "Profile updated"
      sign_in @user
      redirect_to @user
    else
      render 'edit'
    end
  end

  def edit
    #@user = User.find(params[:id])
  end

  def create
  	@user = User.new(user_params)
  	if @user.save
      sign_in @user
  		flash[:success] = "Welcome to the Sample App!"
  		#flash.now[:success] = "Welcome to the Sample App!"
  		redirect_to @user
  	else
  		render 'new'
  	end
  end

  def show
    store_back_location
  	@user = User.find params[:id]
    @microposts = @user.microposts.paginate page:params[:page]
  end

  def new
  	@user = User.new
    @tmp_user = User.all.first
  end

  private
    def admin_user
      redirect_to(root_path) unless current_user.admin?
    end

    def correct_user
      @user = User.find(params[:id])
      redirect_to root_path unless current_user?(@user)
    end

  	def user_params
  		params.require(:user).permit(:name,:email,:password,:password_confirmation,:admin)
  	end
end
